package com.example.gcm;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService  extends GCMBaseIntentService 
{

	@SuppressWarnings("hiding")
	private static final String TAG = "GCMIntentService";

	public GCMIntentService() 
	{
		super("516639321860");
	}

	/**
	 * Issues a notification to inform the user that server has sent a message.
	 */
	private static void generateNotification(Context context, String message) 
	{
		long when = System.currentTimeMillis();
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.ic_launcher,message, when);
		String title = context.getString(R.string.app_name);
		Intent notificationIntent = new Intent(context,GCMActivity.class);
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(context, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notificationManager.notify(0, notification);
	}

	@Override
	protected void onError(Context arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onMessage(Context arg0, Intent arg1) {

		Log.d("GCM", "RECIEVED A MESSAGE");		
		// Get the data from intent and send to notificaion bar
		generateNotification(arg0, arg1.getStringExtra("message"));
		
		Intent broadcastIntent = new Intent();
		broadcastIntent.putExtra("mess", arg1.getStringExtra("message"));
		broadcastIntent.setAction("MESSAGE_RECEIVER");
		getBaseContext().sendBroadcast(broadcastIntent);
	}

	@Override
	protected void onRegistered(Context arg0, String regId) {
		// TODO Auto-generated method stub
		Log.d("GCM", "regId = " + regId);
		Intent broadcastIntent = new Intent();
		broadcastIntent.putExtra("regId", regId);
		broadcastIntent.setAction("REGID_RECEIVER");
		getBaseContext().sendBroadcast(broadcastIntent);
	}

	@Override
	protected void onUnregistered(Context arg0, String arg1) {
		// TODO Auto-generated method stub

	}

}
